package sortedQueue

import (
	"fmt"
)

type comparator[T any] func(a, b T) int

type SortedQueue[T any] struct {
	s []T
	c comparator[T]
}

func New[T any](c comparator[T]) *SortedQueue[T] {
	return &SortedQueue[T]{
		s: []T{},
		c: c,
	}
}

func (q *SortedQueue[T]) Push(e T) {
	if q.Size() == 0 {
		(*q).s = append(q.s, e)
		fmt.Println(q.s)
		return
	}
	switch {
	case q.c(e, q.s[0]) == -1:
		//首位插入
		(*q).s = append([]T{e}, q.s...)
	case q.c(e, q.s[len(q.s)-1]) == 1:
		//末位插入
		(*q).s = append(q.s, e)
	default:
		//中间插入
		for i, t := range q.s {
			if q.c(e, t) <= 0 {
				(*q).s = append(q.s[:i], append([]T{e}, q.s[i:]...)...)
				break
			}
		}
	}
	fmt.Println(q.s)
}

func (q *SortedQueue[T]) Peek() (t T) {
	if q.Size() > 0 {
		t = (q.s)[0]
	}
	return t
}

func (q *SortedQueue[T]) Pop() (t T) {
	if q.Size() > 0 {
		t = q.Peek()
		q.s = q.s[1:]
	}
	return
}

func (q *SortedQueue[T]) Size() int {
	return len(q.s)
}
